package com.oto.web.resource;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.oto.Constants;
import com.oto.model.FlowDO;
import com.oto.util.JAXBUtils;
import com.oto.web.model.Message;
import com.oto.web.model.ObjectFactory;
import com.oto.web.model.XmlPack;
import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2010-11-28
 */
@Path("/flow")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class FlowResource extends BaseResource {
	@GET
	@Path("create")
	public Response createFlow(@DefaultValue("0") @PathParam("packId") long packId) {
		return Response.ok(new Viewable("create", packId)).build();
	}

	@GET
	@Path("{flowId}")
	public Response getFlow(@PathParam("flowId") long flowId) {
		FlowDO flow = flowService.get(flowId);
		return Response.ok(new Viewable("index", flow)).build();
	}

	public List<FlowDO> getFlows() {
		return flowService.latest();
	}

	@GET
	@Path("{flowId}/xml")
	@Produces("application/xml")
	public String getFlowXml(@PathParam("flowId") long flowId) throws JAXBException {
		FlowDO flow = flowService.get(flowId);
		List<FlowDO> flowList = new ArrayList<FlowDO>();
		flowList.add(flow);
		XmlPack xPack = JAXBUtils.generateXMLPackage(flowList);
		List<XmlPack> xPacks = new ArrayList<XmlPack>();
		xPacks.add(xPack);
		Message livingFlow = JAXBUtils.generateLivingFlow(xPacks);
		JAXBElement<Message> je = new ObjectFactory().createMessage(livingFlow);
		StringWriter buffer = new StringWriter();
		JAXBUtils.marshal(Constants.JAXB_CONTEXT_PATH, je, buffer);
		return buffer.toString();
	}

	@POST
	@Path("ajax/create")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain")
	public String postPackageForm(@FormParam("packId") long packId, @FormParam("flow") String json) {
		Gson gson = new Gson();
		FlowDO flow = gson.fromJson(json, FlowDO.class);
		flow.setPackId(packId);
		flow.setOwner(getUserName());
		flowService.add(flow);

		return Constants.STATUS_OK;
	}
}
